package com.springboot.frame.enums;


import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;

/**
 * @author liheng
 * @ClassName EnumValid
 * @Description
 * @date 2020-12-28 14:49
 */
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {ValidEnum.EnumValidator.class})
public @interface ValidEnum {
    String message() default "无效的枚举类型";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * 枚举的类
     *
     * @return
     */
    Class<? extends Enum<?>> enumClass();

    /**
     * 是否忽略空值
     */
    boolean ignoreEmpty() default true;


    class EnumValidator implements ConstraintValidator<ValidEnum, Object> {
        // 枚举校验注解
        private ValidEnum enumValid;

        @Override
        public void initialize(ValidEnum enumValue) {
            this.enumValid = enumValue;
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
            System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            Class<?> cls = this.enumValid.enumClass();
            boolean ignoreEmpty = this.enumValid.ignoreEmpty();
            // target为枚举，并且value有值，或者不忽视空值，才进行校验
            if (value != null || !ignoreEmpty) {
                Object[] objects = cls.getEnumConstants();
                for (Object obj : objects) {
                    // 使用此注解的枚举类需要重写toString方法，改为需要验证的值
                    if (obj.toString().equals(value)) {
                        return Boolean.TRUE;
                    }
                }
            } else {
                return Boolean.TRUE;
            }
            return Boolean.FALSE;
        }
    }
}
